/**
 * Copyright 2019 吉鼎科技.

 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.easyplatform.engine.cmd.swift;

import cn.easyplatform.contexts.RecordContext;
import cn.easyplatform.contexts.SwiftContext;
import cn.easyplatform.contexts.WorkflowContext;
import cn.easyplatform.dos.FieldDo;
import cn.easyplatform.dos.Record;
import cn.easyplatform.entities.beans.table.TableBean;
import cn.easyplatform.interceptor.AbstractCommand;
import cn.easyplatform.interceptor.CommandContext;
import cn.easyplatform.lang.Strings;
import cn.easyplatform.messages.request.CreateSwiftRequestMessage;
import cn.easyplatform.messages.response.CreateSwiftResponseMessage;
import cn.easyplatform.messages.response.GetSwiftResponseMessage;
import cn.easyplatform.messages.vos.swift.LinkRowVo;
import cn.easyplatform.messages.vos.swift.LinkVo;
import cn.easyplatform.messages.vos.swift.TagFieldVo;
import cn.easyplatform.type.EntityType;
import cn.easyplatform.type.IResponseMessage;
import cn.easyplatform.util.MessageUtils;
import cn.easyplatform.util.RuntimeUtils;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;


/**
 * @author <a href="mailto:davidchen@epclouds.com">littleDog</a> <br/>
 * @since 2.0.0 <br/>
 */
public class GetCreateCmd extends AbstractCommand<CreateSwiftRequestMessage> {

	/**
	 * @param req
	 */
	public GetCreateCmd(CreateSwiftRequestMessage req) {
		super(req);
	}

	@Override
	public IResponseMessage<?> execute(CommandContext cc) {
		WorkflowContext ctx = cc.getWorkflowContext();
		LinkVo lv = req.getBody();
		boolean isPreCmd = ctx.getParameterAsString("759").equals("Prev");
		if (isPreCmd && Strings.isBlank(lv.getName())) {
			List<LinkRowVo> data = new ArrayList<LinkRowVo>();
			SwiftContext sc = ctx.getSwift(lv.getId());
			if (sc == null)
				return MessageUtils.swiftNotFound(lv.getId());
			Collection<RecordContext> list = sc.get(lv.getName());
			if (list != null) {
				for (RecordContext rc : list) {
					if (rc.getParameterAsChar("814") != 'D')
						data.add(getRow(rc));
				}
			}
			return new GetSwiftResponseMessage(data);
		}
		TableBean tb = cc.getEntity(lv.getEntity());
		if (tb == null)
			return MessageUtils.entityNotFound(EntityType.TABLE.getName(),
					lv.getEntity());
		SwiftContext sc = null;
		if (Strings.isBlank(lv.getName()))
			sc = ctx.setSwift(lv.getId(), tb, true);
		else
			sc = ctx.getSwift(lv.getId());
		Record record = RuntimeUtils.createRecord(cc, tb, true);
		RecordContext rc = sc.createRecord(record);
		rc.setParameter("857",
				sc.getSize(lv.getParentName(), lv.getParentKeys()) + 1);
		rc.setParameter("833", tb.getId());
		rc.setParameter("814", "C");
		if (!Strings.isBlank(lv.getBefore())) {
			RecordContext parent = null;
			if (Strings.isBlank(lv.getName()))
				parent = ctx.getRecord();
			else
				parent = sc.get(lv.getParentName(), lv.getParentKeys());
			String code = RuntimeUtils.eval(cc, lv.getBefore(), parent, rc);
			if (!code.equals("0000"))
				return MessageUtils.byErrorCode(cc, rc, ctx.getId(), code);
		}
		if (!Strings.isBlank(lv.getAfter()))
			rc.setParameter("837", lv.getAfter());
		sc.appendRecord(lv.getParentName(), lv.getParentKeys(), lv.getName(),
				rc, true);
		return new CreateSwiftResponseMessage(getRow(rc));
	}

	private LinkRowVo getRow(RecordContext record) {
		LinkRowVo row = new LinkRowVo();
		List<TagFieldVo> tags = new ArrayList<TagFieldVo>();
		row.setData(tags);
		row.setKeys(record.getKeyValues());
		for (FieldDo field : record.getData().getData()) {
			if (isTag(field.getDescription())
					|| field.getDescription().endsWith("#")) {
				TagFieldVo tag = new TagFieldVo();
				tag.setLength(field.getLength());
				tag.setTagName(field.getDescription());
				tag.setName(field.getName());
				tag.setType(field.getType());
				tag.setValue(field.getValue());
				//tag.setDescription(field.get);
				tags.add(tag);
			}
		}
		return row;
	}

	private boolean isTag(String name) {
		char[] cs = name.toCharArray();
		if (cs.length < 4) {
			for (int i = 0; i < cs.length; i++) {
				if (Strings.isChineseCharacter(cs[i]))
					return false;
			}
			return true;
		} else
			return false;
	}
}
